<template>
  <div>
    <!-- 年段Tab切换 -->
    <div class="mt-10">
      <el-tabs v-model="activeSectionId" @tab-click="handleSectionChange" type="card">
        <el-tab-pane
            v-for="section in sectionList"
            :key="section.id"
            :label="section.section_name"
            :name="section.id.toString()"
        ></el-tab-pane>
      </el-tabs>
      <el-button type="primary" @click="editCate('add', null)" size="small" plain><i
          class="el-icon-plus"></i>添加动态反馈事项
      </el-button>
    </div>
    
    <div class="table-line-body mt-10 yangTable">
      <el-table
          :data="treeList"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="name" label="动态反馈事项" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="editCate('edit', scope.row)"
            >修改
            </el-button>
            <el-button
                v-if="!scope.row.parent_id"
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="editCate('add', scope.row)"
            >新增
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="deletefn(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="height40"></div>
    <detail :visible.sync="patrolVisible" :optionData="optionData" @InitFn="InitFn"
            :selectList="selectList" :optionType="optionType"></detail>
  </div>
</template>

<script>
import detail from "./detail";
import {DailyFeedbackCateLists, DailyFeedbackCateDelete} from "@/api/admin/dailyFeedback"
import {sectionIndex} from "@/api/admin/class"

export default {
  components: {
    detail
  },
  data() {
    return {
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      arryList: [], // 数据列表
      patrolVisible: false,
      // 搜索
      searchForm: {},
      checkTab: '',
      optionData: null,
      optionType: '',
      treeList: [],
      isExpandAll: false,
      selectList: [],
      // 年段相关
      sectionList: [],
      activeSectionId: ''
    }
  },
  watch: {
  },
  created() {
    this.getSectionList()
  },
  methods: {
    // 获取年段列表
    getSectionList() {
      sectionIndex({p: 0}).then(res => {
        if (!res.code) {
          this.sectionList = res.list.data || [];
          // 默认选中第一个年段
          if (this.sectionList.length > 0) {
            this.activeSectionId = this.sectionList[0].id.toString();
            this.InitFn();
          }
        }
      });
    },

    // 初始化
    async InitFn() {
      console.log('初始化反馈事项数据，当前activeSectionId:', this.activeSectionId);
      
      // 确保section_id有效
      let sectionId = this.activeSectionId;
      
      // 检查sectionId是否存在且有效
      if (!sectionId || sectionId === '' || sectionId === undefined) {
        console.warn('activeSectionId为空，尝试从sectionList获取默认值');
        // 如果activeSectionId为空，尝试从sectionList获取第一个年段ID
        if (this.sectionList && this.sectionList.length > 0) {
          sectionId = this.sectionList[0].id.toString();
          this.activeSectionId = sectionId; // 更新activeSectionId
          console.log('使用第一个年段ID作为默认值:', sectionId);
        } else {
          console.error('无法获取有效的section_id，请求可能会失败');
          return;
        }
      }
      
      // 确保section_id是数字类型
      const numericSectionId = parseInt(sectionId);
      const params = {p: 0, section_id: numericSectionId};
      
      console.log('最终请求参数:', params);
      
      DailyFeedbackCateLists(params).then(res => {
        console.log('获取反馈事项列表响应:', res)
        if (!res.code) {
          // 先按parent_id分组，然后对每个分组内的节点按display_order排序
          const sortedList = this.sortByDisplayOrder(res.list);
          this.treeList = this.$handleTree(sortedList, 'id', 'parent_id');
          let list = this.$handleTree(sortedList, 'id', 'parent_id')
          list.unshift({id: 0, name: '主类目'})
          console.log('处理后的分类列表:', list)
          this.selectList = list
        } else {
          console.error('获取反馈事项失败:', res.msg || '未知错误');
        }
      }).catch(err => {
        console.error('获取反馈事项请求失败:', err);
      })
    },

    // 切换年段
    handleSectionChange(tab) {
      this.activeSectionId = tab.paneName;
      this.InitFn();
    },
    
    // 按display_order排序，同层级内进行比较
    sortByDisplayOrder(list) {
      // 先按parent_id分组
      const grouped = list.reduce((acc, item) => {
        const parentId = item.parent_id || 0;
        if (!acc[parentId]) {
          acc[parentId] = [];
        }
        acc[parentId].push(item);
        return acc;
      }, {});
      
      // 对每个分组内的节点按display_order排序
      Object.keys(grouped).forEach(parentId => {
        grouped[parentId].sort((a, b) => {
          const orderA = a.display_order || 0;
          const orderB = b.display_order || 0;
          return orderA - orderB;
        });
      });
      
      // 重新组合成一维数组
      const sortedList = [];
      // 先添加顶级节点（parent_id为0的节点）
      if (grouped[0]) {
        sortedList.push(...grouped[0]);
        
        // 然后递归添加子节点
        grouped[0].forEach(topNode => {
          this.addSortedChildren(topNode.id, grouped, sortedList);
        });
      }
      
      return sortedList;
    },
    
    // 递归添加已排序的子节点
    addSortedChildren(parentId, grouped, resultList) {
      if (grouped[parentId]) {
        resultList.push(...grouped[parentId]);
        
        grouped[parentId].forEach(node => {
          this.addSortedChildren(node.id, grouped, resultList);
        });
      }
    },
    handleSelectionChange(val) {
      this.handleSelection = val
    },
    deletefn(row) {
      this.$confirm(`确认删除【${row.name}】, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(row.id)
      }).catch(() => {
      })
    },
    async detelRespon(id) {
      DailyFeedbackCateDelete({id:id}).then(res=>{
        if (!res.code) {
          this.$message.success(res.msg)
          this.InitFn()
        }
      })
    },
    editCate(type, row) {
      this.optionType = type
      this.optionData = row
      // 传递当前选中的年段ID
      if (this.optionData) {
        this.optionData.section_id = this.activeSectionId
      } else {
        this.optionData = { section_id: this.activeSectionId }
      }
      this.patrolVisible = true
    }
  },
  mounted() {
  },
}
</script>
<style>
.lead-list {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fddeae;
  margin-bottom: 5px;
  border-radius: 2px;
  padding: 5px 0;
}

.lead-list:last-child {
  margin-bottom: 0;
}

.lead-list span {
  margin-right: 30px;
}
</style>

